<template>
  <div class='clearfix' :class="classname">
    <!-- <div v-if="imgSize" class="img_size">(上传图片不超过{{imgSize/1024}}M)</div> -->
    <a-upload
      :listType="listType"
      :beforeUpload="beforeUpload"
      :customRequest="handleUpload"
      :showUploadList="disabled?{showRemoveIcon:false,showPreviewIcon:false}:showUploadList"
      :fileList="fileList"
      :disabled="disabled"
      @change="handleChange"
      @preview="previewImg"
    >
      <slot>
        <div v-if="fileList.length < max && listType === 'picture-card'">
          <a-icon type="plus" />
          <div class="ant-upload-text">上传图片</div>
        </div>
        <a-button v-if="listType === 'text'">
          <a-icon type="upload" />上传图片
        </a-button>
      </slot>
    </a-upload>
    <div class="img_size">{{imgTips}}</div>
  </div>
</template>
<script>

export default {
  props: {
    /***上传图片类型  product  line */
    imgtype:{
      type:String,
      required:false,
      default:'product'
    },
    /***上传图片建议 tip */
    imgTips:{
      type:String,
      required:false,
      default:'建议尺寸：750 * 750 PX'
    },
    /**
     * 类名 classname 用于重置样式
     */
    classname:{
      type: String,
      required: false,
      default: ''
    },
    /**
     * 上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
     */
    listType: {
      type: String,
      required: false,
      default: 'text'
    },
    /**
     * 是否展示 uploadList, 可设为一个对象，用于单独设定 showPreviewIcon 和 showRemoveIcon
     */
    showUploadList: {
      type: Boolean,
      required: false,
      default: true
    },
    /**
     * 接受一个数组，用于上传列表渲染
     */
    value: {
      type: [Array, String],
      required: false,
      default: () => []
    },
    /**
     * 最大上传数量
     */
    max: {
      type: Number,
      required: false,
      default: 1
    },
    /**
     * 限制上传图片大小
     */
    imgSize: {
      type: Number,
      required: false,
      default: null
    },
    /**
     * 如果value 为String，并用符号分割，可以用此属性做处理。
     */
    symbol: {
      type: String,
      required: false,
      default: undefined
    },
    // 禁止上传
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
  },
  data () {
    return {
      fileList: []
    }
  },
  mounted () {
    this.init()
  },
  watch: {
    value: function (newValue, oldValue) {
      if (newValue !== oldValue) {
        this.init()
      }
    }
  },
  methods: {
    previewImg(file){
      this.$emit('previewImg',file.url)
    },
    init () {
      let { value, symbol } = this
      // 处理接受数据和分发
      if (Array.isArray(value)) {
        this.initFileList(value)
      } else if (typeof value === 'string') {
        if (symbol) {
          this.initFileList(value.split(symbol))
        } else if (value.indexOf(',') > -1) {
          this.initFileList(value.split(','))
        } else {
          // value 是string类型，没有Symbol处理时，为单张图片
          this.fileList = []
          if (value) {
            this.initFileList([value])
          }
        }
      }
    },
    initFileList (arr) {
      arr.forEach((item, index) => {
        let temp = {
          uid: index,
          status: 'done',
          name: item,
          url: item
        }
        this.fileList.push(temp)
      })
    },
    beforeUpload (file) {
      const IsPic = file.type.indexOf('image/') != -1
      if (!IsPic) {
        this.toast('请上传图片', 'error')
        return false
      }
      if (this.fileList.length >= this.max) {
        this.toast('你已达到最大上传数量', 'error')
        return false
      }
      if (this.imgSize && file.size / 1024 > this.imgSize) {
        /**
         * 判断上传图片是否超出大小
         *
         * 暂时留白
         */

        this.toast('上传的图片超过' + this.imgSize/1024 + 'M', 'error')
        return false
      }
      // 上传之前
      file.status = 'uploading'
      this.fileList.push(file)
    },
    handleChange (info) {
      // 上传状态修改回调
      if (info.file.status === 'removed') {
        this.fileList = info.fileList
        this.deliveryData()
      }

      if (info.file.status === 'done') {
        this.deliveryData()
      } else if (info.file.status === 'error') {
        window.console.error('上传失败')
      }
    },
    deliveryData () {
      let imgList = []
      this.fileList.forEach((item) => {
        imgList.push(item.url)
      })
      this.fileList = []

      /**
       * 如果按字符串处理 则按字符串返回
       */
      if (this.symbol && this.max > 1) {
        imgList = imgList.join(this.symbol)
      }

      /**
       * 返回一个组数
       */
      if (this.max === 1) {
        this.$emit('change', imgList[0])
        // 一张图片的时候 添加双向绑定V-model
        this.$emit('input', imgList[0])
      } else {
        this.$emit('input', imgList)
        this.$emit('change', imgList)
      }
    },
    handleUpload (data) {
      let { uid, name, status } = data.file
      let _ = this
      let temp = { uid, name, status }
      let fd = new FormData();
      fd.append('type', _.imgtype)
      fd.append('file', data.file);
       _.axios.post('api/common/upload/image',fd)
        .then(res => {
          console.log(res)
          _.$message.success('上传成功')
          temp.status = 'done'
          temp.url = res.data
          _.fileList.splice(_.fileList.length - 1, 1, temp)
          _.handleChange({ file: temp })
        })
        .catch(() => {
          _.$message.error('上传失败')
          temp.status = 'error'
          _.fileList.splice(_.fileList.length - 1, 1)
          _.handleChange({ file: temp })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
  .img_size {
    color: red;
    font-size: 11px;
    height: 12px;
    line-height: 12px;
    margin-bottom: 5px;
  }
</style>
